package utils

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"ginchat/pkg/lmdb"
	"log"
	"os"
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB

func InitConfig() {
	viper.SetConfigName("app")
	viper.AddConfigPath("config")
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("sqlite config: ", viper.Get("sqlite"))
}

func InitSqlite() *gorm.DB {
	newLogger := logger.New(
		log.New(os.Stdout, "\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second, // 慢SQL阈值
			LogLevel:      logger.Info, // 日志级别
			Colorful:      true,        // 日志颜色
		},
	)
	var err error
	DB, err = gorm.Open(sqlite.Open(viper.GetString("sqlite.dns")),
		&gorm.Config{
			Logger: newLogger,
		})

	if err != nil {
		panic("failed to connect database")
	}
	// user := &models.UserBasic{}
	// DB.Find(user)
	// fmt.Println(user)
	return DB
}

var (
	LmdbEnv *lmdb.DBStore
)

func InitLmdb() *lmdb.DBStore {
	LmdbEnv = lmdb.NewDBStore(viper.GetString("lmdb.dns"))
	return LmdbEnv
}

func CacheSet(key string, data interface{}) error {
	data_bytes, err := json.Marshal(data)
	if err != nil {
		return err
	}

	return LmdbEnv.WriteAll(key, data_bytes)
}

func CacheGet(key string, v any) error {
	data, err := LmdbEnv.ReadAll(key)
	if err == nil {
		err = json.Unmarshal(data, v)
	}
	return err
}
func CacheDel(key string) error {
	return LmdbEnv.Remove(key)
}

func Base64Decode(str string) (dst string) {
	data, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		fmt.Println("error:", err)
	}
	dst = string(data)
	return
}
